package com.tydic.portal.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.*;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.core.utils.ReturnUrlUtil;
import com.tydic.common.mybatis.core.page.TableDataInfo;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.enterprise.domain.Enterprise;
import com.tydic.enterprise.domain.EnterpriseUser;
import com.tydic.enterprise.domain.request.VerifyEnterpriseRequest;
import com.tydic.enterprise.domain.request.VerifyEnterpriseUserRequest;
import com.tydic.enterprise.mapper.EnterpriseChangeHistoryMapper;
import com.tydic.enterprise.mapper.EnterpriseMapper;
import com.tydic.enterprise.service.IEnterpriseService;
import com.tydic.enterprise.service.IEnterpriseUserService;
import com.tydic.system.domain.Account;
import com.tydic.system.domain.Company;
import com.tydic.system.domain.req.CloseUnwantedAuthSignRequest;
import com.tydic.system.domain.req.SeachUnwantedAuthSignRequest;
import com.tydic.system.domain.req.UnwantedAuthSignRequest;
import com.tydic.system.domain.resp.UnwantedAuthSignResponse;
import com.tydic.system.domain.resp.UnwantedAuthSignStatusResponse;
import com.tydic.system.service.IFddService;
import com.tydic.workflow.service.IEnterpriseRegisterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * 企业表Controller
 *
 * @author kin
 * @version 2023-08-15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/portal/enterprise")

public class EnterpriseController {

    private final EnterpriseChangeHistoryMapper enterpriseChangeHistoryDao;
    //    private final IEnterpriseChangeHistoryService historyService;
    private final IEnterpriseService enterpriseService;
    private final IEnterpriseRegisterService enterpriseRegisterService;
    private final IFddService fddService;
    private final IEnterpriseUserService enterpriseUserService;
    private final EnterpriseMapper enterpriseMapper;
    @Value("${fdd.returnUrlPrefix}")
    private String returnUrlPrefix;

    /**
     * 获取数据
     */

    /**
     * 企业信息列表
     */
    @RequestMapping(value = "listData")
    public R listData(Enterprise enterprise, HttpServletRequest request, HttpServletResponse response) {
        // 判断当前登录人获取不同的数据
        return R.ok(TableDataInfo.build(enterpriseMapper.selectList()));
    }


    /**
     * 查询列表数据
     */
    /**
     * 审核企业信息
     */
    @RequestMapping(value = "approveEnterprise")
    public R approveEnterprise(String enterpriseId, String comment, Boolean pass) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        if (Objects.isNull(enterprise)) {
            return R.fail(ResponseCodeEnum.RECORD_NOT_EXIST);
        }
        // 判断是否已经审核了
        if (!enterprise.getAuditStatus().equals(AuditStatusEnum.READY.getStatus())) {
            return R.fail(ResponseCodeEnum.RECORD_IS_AUTH);
        }
        enterpriseService.approveEnterprise(enterprise, comment, pass);
        return R.ok();
    }

    /**
     * 保存数据
     */
    @PostMapping(value = "save")
    /**
     * 申请企业认证
     */
    public R save(@Validated Enterprise enterprise) {
        LoginUser user = LoginHelper.getLoginUser();
        enterprise.setUserCode(user.getUserCode());
        // 获取当前登录人申请的企业记录
        Enterprise temp = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
        if (temp != null) {
            if (temp.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getStatus())) {
                throw new ApiException("该企业已存在!");
            }

            if (temp.getAuditStatus().equals(AuditStatusEnum.READY.getStatus())) {
                throw new ApiException("该企业正在审核!");
            }
            // 审核失败后的重新审核
            else if (temp.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
                boolean finished = enterpriseRegisterService.isFinished(temp.getProcInstId());
                if (!finished) {
                    enterprise.setAuditStatus(AuditStatusEnum.READY.getStatus());
                    enterprise.setProcInstId(temp.getProcInstId());
                }
                enterprise.setId(temp.getId());
                //TODO 这里为什么没保存？
                enterprise.setUpdateDate(new Date());
                enterprise.setUpdateBy(user.getUserCode());
                enterpriseMapper.updateById(enterprise);
            }
        } else {
            //数据库中不存在此记录：
            enterprise.setCreateBy(user.getUserCode());
            enterprise.setCreateDate(new Date());
            //启动审核
            enterpriseService.saveEnterpriseInfo(enterprise);
        }
        return R.ok();
    }


    @PostMapping("/verifyUser")
    /**
     * 企业人员实名认证
     */
    public R verifyUser(@RequestBody @Valid VerifyEnterpriseUserRequest verifyEnterpriseUserRequest) {
        LoginUser user = LoginHelper.getLoginUser();
        // 获取当前登录人申请的企业记录
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
        Account account = fddService.getAccountByMobile(verifyEnterpriseUserRequest.getPhoneNumber());
        String verifyUrl;
        String userCertificationStatus;
        if (account == null) {
            account = new Account();
            account.setMobile(verifyEnterpriseUserRequest.getPhoneNumber());
            account.setUserName(verifyEnterpriseUserRequest.getLegalRepresentative());
            fddService.createAccount(account);
            verifyUrl = fddService.verifyAccount(verifyEnterpriseUserRequest.getLegalRepresentative(), verifyEnterpriseUserRequest.getPhoneNumber(), null, null, ReturnUrlUtil.getEnterpriseVerifyAccountUrl(returnUrlPrefix));
            userCertificationStatus = UserCertificationStatusEnum.READY.getStatus();
        } else {
            if (!StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
                verifyUrl = fddService.verifyAccount(verifyEnterpriseUserRequest.getLegalRepresentative(), verifyEnterpriseUserRequest.getPhoneNumber(), null, null, ReturnUrlUtil.getEnterpriseVerifyAccountUrl(returnUrlPrefix));
            } else {
                verifyUrl = fddService.verifyChangeAccount(verifyEnterpriseUserRequest.getLegalRepresentative(), verifyEnterpriseUserRequest.getPhoneNumber(), null, null, ReturnUrlUtil.getEnterpriseVerifyAccountUrl(returnUrlPrefix));
            }
            userCertificationStatus = account.getVerifyStatus();
        }
        if (enterprise != null) {
            if (enterprise.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getStatus())) {
                throw new ApiException("该企业已完成实名认证，如需变动请发起变更");
            }
            // 审核失败后的重新审核
            else {
                if (enterprise.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
                    boolean finished = enterpriseRegisterService.isFinished(enterprise.getProcInstId());
                    if (!finished) {
                        enterprise.setAuditStatus(AuditStatusEnum.READY.getStatus());
                    }
                }
                enterprise.setLegalRepresentative(verifyEnterpriseUserRequest.getLegalRepresentative());
                enterprise.setPhoneNumber(verifyEnterpriseUserRequest.getPhoneNumber());
                enterprise.setUserCertificationStatus(userCertificationStatus);
                enterpriseService.saveEnterpriseInfo(enterprise);
            }
        } else {
            enterprise = new Enterprise();
            enterprise.setId(IdUtil.getSnowflakeNextIdStr());
            enterprise.setLegalRepresentative(verifyEnterpriseUserRequest.getLegalRepresentative());
            enterprise.setPhoneNumber(verifyEnterpriseUserRequest.getPhoneNumber());
            enterprise.setUserCertificationStatus(userCertificationStatus);
            enterprise.setUserCode(user.getUserCode());
            enterpriseService.saveEnterpriseInfo(enterprise);
        }
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    /**
     * 获取企业法人实名认证状态
     */
    @GetMapping("/getUserCertificationStatus")
    public R getUserCertificationStatus() {
        LoginUser user = LoginHelper.getLoginUser();
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
        if (enterprise == null) {
            throw new ApiException("企业信息不存在");
        }
        return R.ok("成功", enterprise.getUserCertificationStatus());
    }

    /**
     * 获取企业实名认证状态
     */
    @GetMapping("/getEnterpriseCertificationStatus")
    public R getEnterpriseCertificationStatus() {
        LoginUser user = LoginHelper.getLoginUser();
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(user.getUserCode());
        if (enterprise == null) {
            throw new ApiException("企业信息不存在");
        }
        return R.ok("成功", enterprise.getEnterpriseCertificationStatus());
    }


    @PostMapping("/verifyEnterprise")
    /**
     * 企业实名认证
     */
    public R verifyEnterprise(@RequestBody @Valid VerifyEnterpriseRequest verifyEnterpriseRequest) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(currentUser.getUserCode());
        if (enterprise == null) {
            throw new ApiException("该企业不存在，请前往法人代表实名认证");
        }
        Account account = fddService.getAccountByMobile(enterprise.getPhoneNumber());
        if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成法人代表实名认证");
        }
        if (enterprise.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("该企业已完成实名认证，如需变动请发起变更");
        }
        BeanUtils.copyProperties(verifyEnterpriseRequest, enterprise);
        enterprise.setUserCertificationStatus(account.getVerifyStatus());
        Company company = fddService.getCompanyByCompanyName(enterprise.getEnterpriseName());
        String verifyUrl;
        if (company == null) {
            company = new Company();
            company.setCompanyName(enterprise.getEnterpriseName());
            company.setAdminMobile(enterprise.getPhoneNumber());
            company.setAdminName(enterprise.getLegalRepresentative());
            fddService.createCompany(company);
            verifyUrl = fddService.verifyCompany(enterprise.getPhoneNumber(), enterprise.getEnterpriseName(), enterprise.getEnterpriseCode(), enterprise.getBankName(), enterprise.getBankAccount(), enterprise.getBranchBankName(), ReturnUrlUtil.getEnterpriseVerifyCompanyUrl(returnUrlPrefix));
            enterprise.setEnterpriseCertificationStatus(EnterpriseCertificationStatusEnum.READY.getStatus());
        } else {
            if (!StrUtil.equals(company.getIsCerdit(), EnterpriseCertificationStatusEnum.SUCCESS.getStatus())) {
                verifyUrl = fddService.verifyCompany(enterprise.getPhoneNumber(), enterprise.getEnterpriseName(), enterprise.getEnterpriseCode(), enterprise.getBankName(), enterprise.getBankAccount(), enterprise.getBranchBankName(), ReturnUrlUtil.getEnterpriseVerifyCompanyUrl(returnUrlPrefix));
            } else {
                verifyUrl = fddService.verifyChangeCompany(enterprise.getPhoneNumber(), enterprise.getEnterpriseName(), enterprise.getEnterpriseCode(), enterprise.getBankName(), enterprise.getBankAccount(), enterprise.getBranchBankName(), ReturnUrlUtil.getEnterpriseVerifyCompanyUrl(returnUrlPrefix));
            }
            enterprise.setEnterpriseCertificationStatus(company.getIsCerdit());
        }
        if (enterprise.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
            boolean finished = enterpriseRegisterService.isFinished(enterprise.getProcInstId());
            if (!finished) {
                enterprise.setAuditStatus(AuditStatusEnum.READY.getStatus());
            }
        }
        enterpriseService.saveEnterpriseInfo(enterprise);
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    /**
     * 企业开通免验证签服务
     *
     * @return
     */
    @PostMapping("/openUnwantedAuthEnterprise")
    /**
     * 企业开通免验证签服务
     */
    public R openUnwantedAuthEnterprise() {
        String verifyUrl = "";
        LoginUser currentUser = LoginHelper.getLoginUser();
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(currentUser.getUserCode());
        if (enterprise == null) {
            throw new ApiException("该企业不存在");
        }
        Account account = fddService.getAccountByMobile(enterprise.getPhoneNumber());

        if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成法人代表实名认证");
        }
        Company company = fddService.getCompanyByCompanyName(enterprise.getEnterpriseName());

        if (company == null || !company.getIsCerdit().equals("3")) {
            throw new ApiException("未完成企业实名认证");
        }

        SeachUnwantedAuthSignRequest seachUnwantedAuthSignRequest = new SeachUnwantedAuthSignRequest();
        seachUnwantedAuthSignRequest.setAuthorizerFlag(AuthTypeEnum.ENTERPRISE.getType());
        seachUnwantedAuthSignRequest.setAuthorizerTargetId(company.getCompanyId());
        UnwantedAuthSignStatusResponse response = fddService.searchUnwantedAuthSignStatus(seachUnwantedAuthSignRequest);


        //请求签名认证
        UnwantedAuthSignRequest request = new UnwantedAuthSignRequest();
        request.setAuthorizerFlag(AuthTypeEnum.ENTERPRISE.getType());
        request.setAuthorizerTargetId(company.getCompanyId());
        request.setAdminAccountId(account.getAccountId());
        if (response == null) {
            UnwantedAuthSignResponse unwantedAuthSignResponse = fddService.openUnwantedAuthSign(request);
            verifyUrl = unwantedAuthSignResponse.getUrl();
        } else {
            if (NumberUtil.equals(response.getStatus(), UnwantedAuthSignEnum.EFFECT.getType())) {
                return R.ok("已完成免验证签授权状态");
            }
            UnwantedAuthSignResponse unwantedAuthSignResponse = fddService.openUnwantedAuthSign(request);
            verifyUrl = unwantedAuthSignResponse.getUrl();

        }
        enterprise.setOpenAuthSignStatus(EnableEnum.DISABLE.getStatus());
        enterpriseService.saveEnterpriseInfo(enterprise);
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    /**
     * 企业关闭免验证签服务
     *
     * @return
     */
    @PostMapping("/closeUnwantedAuthEnterprise")
    /**
     * 企业关闭免验证签服务
     */
    public R closeUnwantedAuthEnterprise() {
        String verifyUrl = "";
        LoginUser currentUser = LoginHelper.getLoginUser();
        Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(currentUser.getUserCode());
        if (enterprise == null) {
            throw new ApiException("该企业不存在");
        }
        Account account = fddService.getAccountByMobile(enterprise.getPhoneNumber());

        if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成法人代表实名认证");
        }
        Company company = fddService.getCompanyByCompanyName(enterprise.getEnterpriseName());

        if (company == null || !company.getIsCerdit().equals("3")) {
            throw new ApiException("未完成企业实名认证");
        }

        SeachUnwantedAuthSignRequest seachUnwantedAuthSignRequest = new SeachUnwantedAuthSignRequest();
        seachUnwantedAuthSignRequest.setAuthorizerFlag(AuthTypeEnum.ENTERPRISE.getType());
        seachUnwantedAuthSignRequest.setAuthorizerTargetId(company.getCompanyId());
        UnwantedAuthSignStatusResponse response = fddService.searchUnwantedAuthSignStatus(seachUnwantedAuthSignRequest);

        if (response != null && !NumberUtil.equals(response.getStatus(), UnwantedAuthSignEnum.EFFECT.getType())) {
            return R.ok("当前企业并非免验证签状态");
        }

        //请求签名认证
        CloseUnwantedAuthSignRequest request = new CloseUnwantedAuthSignRequest();
        request.setAuthorizerFlag(AuthTypeEnum.ENTERPRISE.getType());
        request.setAuthorizerTargetId(company.getCompanyId());
        fddService.closeUnwantedAuthSign(request);

        enterprise.setOpenAuthSignStatus(EnableEnum.DISABLE.getStatus());
        enterpriseService.saveEnterpriseInfo(enterprise);
        return R.ok("成功");
    }

    /**
     * 获取企业信息
     */
    @GetMapping("/getEnterprise")
    @ResponseBody
    public R getEnterprise() {
        LoginUser currentUser = LoginHelper.getLoginUser();
        Enterprise enterprise;
        if (StrUtil.equals(currentUser.getUserType(), UserTypeEnum.ENTERPRISE.getUserType())) {
            enterprise = enterpriseService.getEnterpriseByUserCode(currentUser.getUserCode());
        } else {
            EnterpriseUser enterpriseUser = enterpriseUserService.findByUserCode(currentUser.getUserCode());
            enterprise = enterpriseService.getEnterById(enterpriseUser.getEnterpriseId());
        }
        return R.ok(enterprise);
    }


    /**
     * 获取企业信息审核待办
     */
    @GetMapping("getNeedHandler")
    public R getNeedHandler() {
        return R.ok(0);
    }

    /**
     * 获取企业信息
     */
    @RequestMapping(value = "get")
    public Enterprise get(String id) {
        return enterpriseService.getEnterById(id);
    }

}
